import { useState, useRef, useEffect } from 'react'
import httpApi from "./index"
import { useQuery } from '@realm/react'
import { schemaName } from "../realm"
const token_type = "Bearer"


const useWebsocket = (url = httpApi.wsapiWs) => {
    const Token = useQuery(schemaName.UserInfo, userInfo => {
        return userInfo.filtered('Current = true');
    })[0]?.Token
    const ws = useRef(null)
    // socket 数据
    const [wsData, setMessage] = useState({})
    //  socket 状态
    const [readyState, setReadyState] = useState({ key: 0, value: '正在连接中' })

    const creatWebSocket = () => {
        const stateArr = [
            { key: 0, value: '正在连接中' },
            { key: 1, value: '已经连接并且可以通讯' },
            { key: 2, value: '连接正在关闭' },
            { key: 3, value: '连接已关闭或者没有连接成功' },
        ]
        try {
            ws.current = new WebSocket(url, null, { headers: { Authorization: token_type + ' ' + Token } })


            ws.current.onopen = () => {
                setReadyState(stateArr[ws.current?.readyState ?? 0])
            }
            ws.current.onclose = () => {
                setReadyState(stateArr[ws.current?.readyState ?? 0])
            }
            ws.current.onerror = () => {
                setReadyState(stateArr[ws.current?.readyState ?? 0])
            }
            ws.current.onmessage = (e) => {
                setMessage({ ...JSON.parse(e.data) })
            }

        } catch (error) {
        }
    }

    const webSocketInit = () => {
        if (!ws.current || ws.current.readyState === 3) {
            creatWebSocket()
        }
    }

    //  关闭 WebSocket
    const closeWebSocket = () => {
        ws.current?.close()
    }

    // 发送数据
    const sendMessage = (str) => {
        ws.current?.send(str)
    }

    //重连
    const reconnect = () => {
        try {
            closeWebSocket()
            ws.current = null
            creatWebSocket()
        } catch (e) {
            console.log(e)
        }
    }

    useEffect(() => {
        webSocketInit()
        return () => {
            ws.current?.close()
        }
    }, [ws])

    // useEffect(() => {
    //     reconnect()
    // }, [Token])

    return {
        wsData,
        readyState,
        closeWebSocket,
        reconnect,
        sendMessage,
        ws
    }
}
export default useWebsocket
